package com.example.pan.ui.file

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.view.ActionMode
import androidx.appcompat.widget.PopupMenu
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.pan.R
import com.example.pan.databinding.FragmentDriveFileBinding
import com.example.pan.model.FileInfo
import com.example.pan.ui.copy
import com.hi.dhl.binding.viewbind
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch


@AndroidEntryPoint
class DriveFileFragment : Fragment(R.layout.fragment_drive_file) {

    private val mViewModel: DriveFileViewModel by viewModels()
    private val adapter = ListFileInfoAdapter()
    private val binding: FragmentDriveFileBinding by viewbind()

    val actionMode: ActionMode.Callback = object : ActionMode.Callback {
        override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            mode?.title = "Chooser"
            mode?.menuInflater?.inflate(R.menu.fragment_folder_menu, menu)
            return true
        }

        override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            return false
        }

        override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
            return false
        }

        override fun onDestroyActionMode(mode: ActionMode?) {
        }

    }


    private var listFileJob: Job? = null
    private var token: String? = null

    @ExperimentalCoroutinesApi
    fun listFile(token: String, dir: String) {
        listFileJob?.cancel()
        listFileJob = lifecycleScope.launch {
            mViewModel.listFile(token, dir).collect {
                adapter.submitData(it)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
        arguments?.getString("token")?.let {
            token = it
        }
    }

    @ExperimentalCoroutinesApi
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        token?.let { listFile(it, "/") }
        val recyclerView = binding.recyclerView
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = adapter
        recyclerView.itemAnimator = DefaultItemAnimator()
        adapter.addLoadStateListener { loadState ->
            binding.refreshLayout.isRefreshing = loadState.refresh == LoadState.Loading
            if (loadState.refresh is LoadState.Error) {
                val error = loadState.refresh as LoadState.Error
                Toast.makeText(context, error.error.message, Toast.LENGTH_SHORT).show()
            }
        }
        adapter.setOnItemClickListener(object : ListFileInfoAdapter.OnItemClickListener {
            override fun onItemClick(item: FileInfo) {
                if (item.isdir == 1) {
                    token?.let { listFile(it, item.path) }
                    return
                }
                if (item.category == 1) {
                    mViewModel.filemetas(item.fs_id).observe(viewLifecycleOwner, {
                        val intent = Intent(context, MediaPlayerActivity::class.java)
                        intent.putExtra("url", it.dlink)
                        startActivity(intent)
                    })
                }
                // (activity as AppCompatActivity).startSupportActionMode(actionMode)
            }

            override fun onMoreFunClick(item: FileInfo, view: View) {
                showMenu(item, view)
            }

            override fun onBackClick() {
                mViewModel.onBackDir()
            }
        })
        binding.refreshLayout.setOnRefreshListener {
            adapter.refresh()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.activity_main_menu, menu)
    }

    @ExperimentalCoroutinesApi
    private fun showMenu(item: FileInfo, view: View) {
        val popup = PopupMenu(requireContext(), view)
        popup.menuInflater.inflate(R.menu.fragment_folder_menu, popup.menu)
        popup.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.menu_rename, R.id.menu_move, R.id.menu_delete -> {
                    Toast.makeText(context, getString(R.string.coding), Toast.LENGTH_SHORT).show()
                }
                R.id.menu_dlink -> {
                    if (item.isdir == 1) {
                        Toast.makeText(context, getString(R.string.not_support), Toast.LENGTH_SHORT)
                            .show()
                    } else {
                        mViewModel.filemetas(item.fs_id).observe(viewLifecycleOwner) { fileMeta ->
                            AlertDialog.Builder(requireContext())
                                .setTitle(fileMeta.filename)
                                .setMessage(fileMeta.dlink)
                                .setNegativeButton(getString(R.string.copy_link)) { _, _ ->
                                    copy(fileMeta.dlink, requireContext())
                                    Toast.makeText(
                                        context,
                                        getString(R.string.copy_success),
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                                .setPositiveButton(getString(R.string.direct_download)) { _, _ ->
                                    mViewModel.download(fileMeta.dlink, fileMeta.filename)
                                }
                                .create().show()
                        }
                    }
                }
            }
            true
        }
        popup.show()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.menu_search -> {
                findNavController().navigate(R.id.navigation_download)
                true
            }
            else -> super.onOptionsItemSelected(item)

        }
    }
}